<template>
  <li>
    <label>
      <!-- <input type="checkbox" v-model="todo.done" /> -->
      <input
        type="checkbox"
        :checked="todo.done"
        @change="changeHandler(todo.id)"
      />
      <input
        v-show="isEditing"
        type="text"
        v-model="title"
        @keyup.enter="editHandler"
        @blur="editHandler"
        ref="titleRef"
      />
      <span v-show="!isEditing">{{ title }}</span>
    </label>

    <button class="btn btn-danger" @click="delHandler(todo.id)">删除</button>
    <button
      class="btn btn-primary"
      v-show="!isEditing"
      @click="editBtnClickHandler"
    >
      编辑
    </button>
  </li>
</template>

<script>
import PubSub from "pubsub-js";
import { EVENT_CHECK_ITEM, EVENT_EDIT_ITEM, MSG_DELETE_ITEM } from "../consts";

export default {
  name: "Item",
  data() {
    return { isEditing: false, title: "" };
  },
  props: ["todo"],
  mounted() {
    this.title = this.todo.title;
  },
  methods: {
    changeHandler(id) {
      this.$bus.$emit(EVENT_CHECK_ITEM, id);
    },
    delHandler(id) {
      if (window.confirm("确认删除")) {
        PubSub.publish(MSG_DELETE_ITEM, id);
      }
    },
    editHandler() {
      this.isEditing = false;
      this.$bus.$emit(EVENT_EDIT_ITEM, { ...this.todo, title: this.title });
    },
    editBtnClickHandler() {
      this.isEditing = true;

      // vue 会将整个回调执行完毕之后才进行DOM渲染，所以直接写 focus() 不会奏效（此时input的display:none）
      // $nextTick 会告诉 vue，在完成DOM渲染后再执行
      this.$nextTick(() => {
        this.$refs.titleRef.focus();
      });
    },
  },
};
</script>

<style scoped lang="scss">
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background: #ddd;

  button {
    display: block;
  }
}
</style>
